package com.lzy.cloud.job.init;

import com.lzy.cloud.job.dtos.JobInfoDto;
import com.lzy.cloud.job.service.JobInfoService;
import com.lzy.cloud.job.utils.QuartzUtil;
import org.joda.time.LocalDateTime;
import org.quartz.Scheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class InitJob implements ApplicationListener<ContextRefreshedEvent> {
    private static final Logger LOGGER = LoggerFactory.getLogger(InitJob.class);

    @Autowired
    private JobInfoService jobInfoService;
    @Autowired
    @Qualifier("quartzScheduler")
    Scheduler scheduler;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        //初始化加载所有定时任务
        if (event.getApplicationContext().getParent().getParent() == null) {
            intJobs();
        }
    }

    public void intJobs() {

        LOGGER.debug("添加定时任务开始..." + LocalDateTime.now());

        // 获取所有的任务
        List<JobInfoDto> jiDTOList = jobInfoService.getAllJobs();
        for (JobInfoDto myJob : jiDTOList) {
            try {
                QuartzUtil.addJob(myJob, scheduler);
            } catch (Exception e) {
                LOGGER.error("任务名称 = [" + myJob.getJobName() + "]======未启动成功，请检查是否配置正确!", e);
            }
        }
    }
}
